package accounting.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import accounting.model.Income;

@Transactional
public class IncomeServiceImpl implements IncomeService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<Income> findAll() {
        Query query = getEntityManager().createQuery("SELECT a FROM Income a ORDER BY incomeDate ASC");
        return query.getResultList();
    }

    private void save(Income income) {
        if (income.getId() == null) {
            // new
            em.persist(income);
        } else {
            // update
            em.merge(income);
        }
    }

    public void remove(int id) {
        Income income = find(id);
        if (income != null) {
            em.remove(income);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public Income find(int id) {
        return em.find(Income.class, id);
    }

    public void add(Income income) {
        System.out.print(income.getIncomeDate());
        this.save(income);
    }

    public void update(Income income) {
        this.save(income); 
    }

}
